package com.xth8013.as.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xth8013.as.domain.User;
import com.xth8013.as.service.SecurityService;
import org.springframework.beans.factory.annotation.Value;


public class SSOAuth extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7096861280473726119L;

	// 存储所有用户的ticket
	private static ConcurrentMap<String, String> SSOIDs;
	@Value("${sso.cookiename}")
	String cookiename = "First_SSO_PRJ_ID";
	@Value("${sso.domainname}")
	String domainname = null;

	private SecurityService securityService;

	protected org.springframework.web.context.WebApplicationContext wac; // WEB程序上下文环境

	@Override
	public void init() throws ServletException {
		wac = org.springframework.web.context.support.WebApplicationContextUtils
				.getWebApplicationContext(super.getServletContext());
		securityService = (SecurityService) wac.getBean("securityService"); // spring的组件都行，包含@Component，@Service，@Repository等等

	}

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		SSOIDs = new ConcurrentHashMap<String, String>();
		wac = org.springframework.web.context.support.WebApplicationContextUtils
				.getWebApplicationContext(super.getServletContext());
		securityService = (SecurityService) wac.getBean("securityService"); // spring的组件都行，包含@Component，@Service，@Repository等等。

	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		String result = "failed";
		if (action == null) {
			handlerFromLogin(request, response);
		} else if (action.equals("authcookie")) {
			String myCookie = request.getParameter("cookiename");
			if (myCookie != null)
				result = authCookie(myCookie);
			out.print(result);
			out.close();
		} else if (action.equals("authuser")) {
			result = authNameAndPasswd(request, response);
			out.print(result);
			out.close();
		} else if (action.equals("logout")) {
			String myCookie = request.getParameter("cookiename");
			logout(myCookie);
			out.close();
		}
	}

	public String authCookie(String value) {
		String result = (String) SSOIDs.get(value);
		if (result == null) {
			result = "failed";
			System.out.println("Authentication failed!");
		} else {
			System.out.println("Authentication success!");
		}
		return result;
	}

	public String authUserAndPass(String username, String password) {

		try {
			// 验证登录状况
			User user = securityService.login(username, password);
			String newID = createUID();
			// 存入map
			SSOIDs.put(newID, username);
			return username;
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}

	}

	protected String authNameAndPasswd(HttpServletRequest request,
			HttpServletResponse response) {
		String username = request.getParameter("userAccount");
		String password = request.getParameter("userPwd");

		// 验证登录状况
		try {
			User user = securityService.login(username, password);
			String newID = createUID();
			SSOIDs.put(newID, username);
			return newID;
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public String getServletInfo() {
		return "Short description";
	}




	/**
	 * 注销
	 * 
	 * @param UID
	 */
	private void logout(String UID) {
		System.out.println("Logout for " + UID);
		SSOIDs.remove(UID);
	}

	/**
	 * 创建ticket
	 * 
	 * @return
	 */
	private static String createUID() {
		Date now = new Date();
		long time = now.getTime();
		return "Xth" + time;
	}

	/**
	 * 验证用户名、密码，然后跳回原页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void handlerFromLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("userAccount");
		String password = request.getParameter("userPwd");
		try {
			User user = securityService.login(username, password);
			String gotoURL = request.getParameter("goto");
			String newID = createUID();
			SSOIDs.put(newID, username);

			this.add2Cookie(response, this.cookiename, newID, 60 * 1000);

			System.out.println(cookiename + ":" + newID);
			if (gotoURL != null && gotoURL.length() > 0 && !gotoURL.equalsIgnoreCase("null")) {
				System.out.println("login success, goto back url:" + gotoURL);
				PrintWriter out = response.getWriter();
				response.sendRedirect(gotoURL);
				out.close();
			} else {
				PrintWriter out = response.getWriter();
				response.sendRedirect("/as/mainController/toMainMenu");
				out.close();
				// request.setAttribute("loginedUserAccount",
				// user.getUserAccount());
				// request.getRequestDispatcher("").forward(request, response);
			}

		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("loginMsg", e.getMessage());
			request.getRequestDispatcher("/securityController/toLogin").forward(request, response);
		}

	}

	/**
	 * 添加至cookie
	 * 
	 * @param response
	 * @param cookiename
	 * @param cookieValue
	 * @param maxAge
	 */
	private void add2Cookie(HttpServletResponse response, String cookiename,
			String cookieValue, int maxAge) {
		Cookie cookie = new Cookie(cookiename, cookieValue);
		// cookie.setDomain(this.domainname);
		cookie.setPath("/");
		cookie.setMaxAge(maxAge); // cookie一年内有效60*60*24*365
		response.addCookie(cookie);
	}
}